<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-22 23:13:35
 * @LastEditTime: 2024-05-21 22:13:32
 * @FilePath: \env-manager-pc\src\views\statistics\online\index.vue
-->
<script setup lang="ts">
import { floor, isBoolean } from 'lodash-es'
import statisticsApi from '@/api/modules/statistics'
import { usePage } from '@/utils/commonHook'
import { useEnvOrgs, useOwnerOrgs } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import useKeepAliveStore from '@/store/modules/keepAlive'

defineOptions({
  name: 'StatisticsDataFullList',
})
const keepAliveStore = useKeepAliveStore()

const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: ['DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter',
    'DIM.Business.DeviceFilters.EntNameFilter',
    'DIM.Devices.Filters.OwnerOrgGUIDFilter',
    'DIM.Devices.Filters.NameFilter',
    'DIM.Devices.Filters.AssetCodeFilter'],
}))

const formData = reactive({
  OnlineState: null,
})

function search() {
  page.PageNum = 1
  getTableData()
}

const loading = ref(false)
async function getTableData() {
  loading.value = true
  const res = await statisticsApi.GetDeviceCurrentRunInfo({
    objFilter: {
      Type: 'DIM.FilterCollection',
      LogicOperator: 0,
      Filters: [...searchData.getQuery().Filters, {
        Type: 'DIM.Devices.Filters.IsOnline',
        OnlineState: isBoolean(formData.OnlineState) ? formData.OnlineState : null,
      }],
    },
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  const { Rows, RecordsetCount } = res as any
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function toDetail() {
  // sessionStorage.setItem('ent_data', JSON.stringify(row))
  // router.push(`/statistics/data-full/${row.EntObjID}`)
}

const OwnerList = useOwnerOrgs()
const envOrgs = useEnvOrgs()
const defaultProps = {
  children: 'Children',
  label: 'Name',
}

onBeforeRouteLeave((to) => {
  if (to.name === 'statistics-data-full-detail') {
    keepAliveStore.add('StatisticsDataFullList')
  }
  else {
    keepAliveStore.remove('StatisticsDataFullList')
  }
})

function duration(timeLong: number): string {
  const hour = Number.parseInt((timeLong / 3600).toString())
  const minute = (timeLong - 3600 * hour) / 60
  return `${hour}小时${floor(minute, 2)}分钟`
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.DeviceFilters.EnvOrgGUIDFilter']"
                  value-key="Code"
                  :data="envOrgs"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Business.DeviceFilters.EntNameFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="设备名称">
                <ElInput v-model="searchData['DIM.Devices.Filters.NameFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="在线状态">
                <ElSelect v-model="formData.OnlineState" class="w-full" clearable>
                  <ElOption label="在线设备" :value="true" />
                  <ElOption label="离线设备" :value="false" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Devices.Filters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  :data="OwnerList"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="设备编码">
                <ElInput v-model="searchData['DIM.Devices.Filters.AssetCodeFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="6" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <!-- <ElButton type="warning">
                导出
              </ElButton> -->
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          border
          header-align="center"
          height="100%"
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn title="序号" type="seq" width="80" align="center" />
          <VxeColumn field="EnvOrgName" title="管理机构" width="120" />
          <VxeColumn field="OwnerOrgName" title="运维公司" width="120" />
          <VxeColumn field="EntName" title="企业名称" min-width="200" show-overflow>
            <template #default="{ row }">
              <ElButton link @click="toDetail()">
                {{ row.EntName }}
              </ElButton>
            </template>
          </VxeColumn>
          <VxeColumn field="DeviceName" title="设备名称" width="240" header-align="center" />
          <VxeColumn field="DeviceAsset" title="设备编码" width="300" header-align="center" />
          <VxeColumn field="OnlineStateName" title="在线状态" width="120" header-align="center" />
          <VxeColumn field="LastReceiveDataTime" title="最后通讯时间" width="180" header-align="center" />
          <VxeColumn field="PowerSupplyStateName" title="供电状态" width="120" header-align="center" />
          <VxeColumn field="LastPowerSupplyTime" title="最后停上电时间" width="180" header-align="center" />
          <VxeColumn field="LastElecDataTime" title="最后上报数据时间" width="180" header-align="center" />
          <VxeColumn field="DisappearTime" title="最后失联时间" width="180" header-align="center" />
          <VxeColumn field="DisappearDuration" title="时间（小时）" width="180" header-align="center">
            <template #default="{ row }">
              {{ duration(row.DisappearDuration) }}
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
  </div>
</template>
